<template>
    <div>
        <div class="upload-item"
             v-for="(item,index) in ImagesFilesArr"
             :key="index">
            <img :src="item.url"
                 :preview="preview"
                 alt="">
            <span v-if="!imgList"
                  @click="ImagesFilesRemove(index)"></span>
        </div>
        <div class="upload-item"
             v-for="(item,index) in uploadImgs"
             :key="item+index">
            <img :src="item.url"
                 :preview="preview"
                 alt="">
            <span v-if="!imgList"
                  @click="removeImg(item.name,index)"></span>
        </div>
        <div class="upload-item"
             v-if="!imgList&&(uploadImgs.length+ImagesFilesArr.length)<limitNumber">
            <!-- <img src="@static/images/upload.png"
                 alt=""> -->
            <label for="file"></label>
            <input type="file"
                   id="file"
                   accept="image/*"
                   @change="upload"
                   multiple="multiple"
                   key="1"
                   v-if="showUpload">
            <input type="file"
                   id="file"
                   accept="image/*"
                   @change="upload"
                   key="2"
                   multiple="multiple"
                   v-else>
        </div>
    </div>
</template>
<script>
import formatDate from '@/utils/formatDate'
export default {
    name: 'upload',
    data () {
        return {
            uploadImgs: [], // 图片上传回传的照片
            preview: '', // 预览图片分组
            // uploadImgs: [], // 图片上传回传的照片
            uploadImgForm: '', // 图片上传formData对象
            // images: [],
            ImagesFilesArr: [],
            showUpload: true
        }
    },
    props: {
        imgList: {
            default: ''
        },
        images: {
            default: () => []
        },
        uploadImgss: {
            default: () => []
        },
        uploadImgFormData: {
            default: ''
        },
        newBlobList: {
            default: () => []
        },
        ImagesFiles: {
            default: () => []
        },
        limitNumber: {
            default: 10
        },
        hasWatermark: {
            default: false
        }
    },
    created () {
        this.uploadImgForm = this.uploadImgFormData
        this.uploadImgs = this.uploadImgss
        this.preview = new Date().getTime()
        if (this.imgList) {
            this.imgList.forEach(item => {
                this.uploadImgs.push({
                    url: item
                })
            })
        }
    },
    watch: {
        imgList (newVal, oldVal) {
            console.log(oldVal)
            console.log(newVal)
        },
        uploadImgss (newVal, oldVal) {
            this.uploadImgs = newVal
        },
        ImagesFiles (newVal) {
            this.ImagesFilesArr = newVal
        }
    },
    methods: {
        upload (e) {
            let This = this
            for (const key in e.target.files) {
                if (!e.target.files.hasOwnProperty(key)) {
                    this.showUpload = !this.showUpload
                    return false
                }
                if (key !== 'length') {
                    let file = e.target.files[key]
                    if (file.type.indexOf('image') == 0) {
                        let reader = new FileReader()
                        let x = new Date().getTime()
                        let cc = (file.type).substring(6)

                        file = new File([file], x + '.' + cc, { type: file.type })
                        reader.readAsDataURL(file)
                        reader.onload = function (e) {
                            if ((This.uploadImgs.length + This.ImagesFilesArr.length) < This.limitNumber) {
                                if (file.size / 1024 > 1025 || This.hasWatermark) { // 判断图片的大小，超过1M 进行压缩
                                    let result = e.target.result // base64格式图片地址
                                    let image = new Image()
                                    image.src = result // 设置image的地址为base64的地址
                                    image.onload = function () {
                                        if ((This.uploadImgs.length + This.ImagesFilesArr.length) < This.limitNumber) {
                                            var canvas = document.createElement('canvas')
                                            var context = canvas.getContext('2d')
                                            canvas.width = image.width // 设置canvas的画布宽度为图片宽度
                                            canvas.height = image.height
                                            context.drawImage(image, 0, 0, image.width, image.height) // 在canvas上绘制图片
                                            This.watermark(context, image.width, image.height)
                                            let dataUrl = canvas.toDataURL('image/jpeg', 0.3) // 0.92为压缩比，可根据需要设置，设置过小会影响图片质量
                                            // dataUrl 为压缩后的图片资源，可将其上传到服务器
                                            let newBlob = This.convertBase64UrlToBlob(dataUrl, file)
                                            // if (newBlob.size / 1024 > 1025) {
                                            if (newBlob.size / 1024 > 2048) {
                                                This.$vux.toast.text('图片过大，请重新上传...')
                                                return false
                                            }
                                            if (This.uploadImgForm) {
                                                This.uploadImgForm.append(x, newBlob)
                                            } else {
                                                let formData = new FormData()
                                                formData.append(x, newBlob)
                                                This.uploadImgForm = formData
                                            }
                                            // This.emitFormData(file, `data:image/png;base64,${e.target.result.split('base64,')[1]}`, x, newBlob)
                                            This.emitFormData(file, dataUrl, x, newBlob)
                                        } else {
                                            This.$vux.toast.text(`最多只能上传${This.limitNumber}图片`)
                                        }
                                    }
                                } else {
                                    if (This.uploadImgForm) {
                                        This.uploadImgForm.append(x, file)
                                    } else {
                                        let formData = new FormData()
                                        formData.append(x, file)
                                        This.uploadImgForm = formData
                                    }
                                    This.emitFormData(file, `data:image/png;base64,${e.target.result.split('base64,')[1]}`, x, file)
                                }
                            } else {
                                This.$vux.toast.text(`最多只能上传${This.limitNumber}图片`)
                            }
                        }
                    }
                }
            }
        },
        clickinput () {
            this.$refs.inputlist.click()
        },
        removeImg (name, index) {
            this.uploadImgs.splice(index, 1)
            this.images.splice(index, 1)
            this.newBlobList.splice(index, 1)
            this.uploadImgForm.delete(name)
            this.$emit('setFormData', this.uploadImgForm, this.uploadImgs.length, this.uploadImgs, this.images, this.newBlobList)
        },
        emitFormData (file, url, x, newBlob) {
            this.uploadImgs.unshift({
                url: url,
                name: x
            })
            this.images.unshift(file)
            this.newBlobList.unshift(newBlob)

            this.$emit('setFormData', this.uploadImgForm, this.uploadImgs.length, this.uploadImgs, this.images, this.newBlobList)
            this.$nextTick(() => {
                this.$previewRefresh()
            })
        },
        convertBase64UrlToBlob (urlData, file) {
            let arr = urlData.split(',')
            let mime = arr[0].match(/:(.*?);/)[1]
            let bstr = atob(arr[1])
            let n = bstr.length
            let u8arr = new Uint8Array(n)
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
            }
            // let typelist = file.type;
            // let y=typelist.substring(6);
            let trueblob = new Blob([u8arr], { type: mime })
            return new window.File([trueblob], file.name, { type: file.type })
        },
        ImagesFilesRemove (index) {
            this.ImagesFilesArr.splice(index, 1)
            console.log(this.$parent.ImagesFiles)
            this.$parent.ImagesFiles = this.ImagesFilesArr
            console.log(this.$parent.ImagesFiles)
        },
        watermark (context, width, height) {
            let currentDate = formatDate()
            let newDate = new Date()
            let hours = newDate.getHours() >= 10 ? newDate.getHours() : `0${newDate.getHours()}`
            let minutes = newDate.getMinutes() >= 10 ? newDate.getMinutes() : `0${newDate.getMinutes()}`
            let seconds = newDate.getSeconds() >= 10 ? newDate.getSeconds() : `0${newDate.getSeconds()}`
            context.font = '24px Microsoft YaHe'
            context.fillStyle = 'rgba(252,0,0,0.8)'
            context.fillText(`时间：${currentDate} ${hours}:${minutes}:${seconds}`, width - 350, height - 20)
        }
    }
}
</script>
<style>
.upload-item {
    position: relative;
}
.newinputlist {
    position: absolute;
    top: 0;
    left: 0;
    opacity: 0;
}
</style>
